import win32com.client
import sys
import contextlib
import winreg as reg
# 资料来源 PCI 设备的标识符 https://learn.microsoft.com/zh-cn/windows-hardware/drivers/install/identifiers-for-pci-devices
def extract_info(s):
    # 查找VEN_后的四位
    ven_start = s.find('VEN_') + 4
    ven_end = ven_start + 4
    ven_code = s[ven_start:ven_end]
    
    # 查找DEV_后的四位
    dev_start = s.find('DEV_') + 4
    dev_end = dev_start + 4
    dev_code = s[dev_start:dev_end]
    
    # 查找SUBSYS_后的八位
    subsys_start = s.find('SUBSYS_') + 7
    subsys_end = subsys_start + 8
    subsys_code = s[subsys_start:subsys_end]
    
    return ven_code, dev_code, subsys_code

class RedirectStdout:
    def __init__(self, new_target):
        self._new_target = new_target

    def __enter__(self):
        self._old_target, sys.stdout = sys.stdout, self._new_target

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout = self._old_target

# 假设你要打印的内容包括多行
print("This will be printed to the screen.")
def get_display_adapters():
    # 创建 WMI 对象
    wmi = win32com.client.GetObject("winmgmts:")
    
    # 查询显示适配器
    adapters = wmi.ExecQuery("SELECT * FROM Win32_VideoController")
    
    # 遍历显示适配器并打印信息
    for adapter in adapters:
        print(f"名称: {adapter.Name}")
        print(f"设备 ID: {adapter.DeviceID}")
        print(f"驱动版本: {adapter.DriverVersion}")
        pnp_device_id = adapter.PNPDeviceID
        print(f"供应商: {pnp_device_id}")
        #print(f"ID: {adapter.graphicscard}")
        # 检查 AdapterRAM 是否为 None
        # 资料来源 PCI 设备的标识符 https://learn.microsoft.com/zh-cn/windows-hardware/drivers/install/identifiers-for-pci-devices

        if 'NVIDIA' in adapter.Name:
            ven_code, dev_code, subsys_code = extract_info(pnp_device_id)
            print(f"VEN_ Code: {ven_code}")
            print(f"DEV_ Code: {dev_code}")
            print(f"SUBSYS_ Code: {subsys_code}")
            print(f"{ven_code}&{dev_code}&{subsys_code};")
            #P102 = (f"{ven_code}&{dev_code}&{subsys_code};")
            class RedirectStdout:
                def __init__(self, new_target):
                    self._new_target = new_target

                def __enter__(self):
                    self._old_target, sys.stdout = sys.stdout, self._new_target

                def __exit__(self, exc_type, exc_val, exc_tb):
                    sys.stdout = self._old_target

        # 假设你要打印的内容包括多行
            with open("regnvidiaHighPerfAdapter.reg", "w") as f, RedirectStdout(f):
                
                print("Windows Registry Editor Version 5.00")
                print( )
                print("[HKEY_CURRENT_USER\Software\Microsoft\DirectX]")
                print( )     
                print("[HKEY_CURRENT_USER\Software\Microsoft\DirectX\GraphicsSettings]")
                print(f'"SpecificGPUOptionApplicable"=dword:00000002')
                print(f'"DefaultHighPerfGPUApplicable"=dword:00000001')
                print( )
                print("[HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\DirectX\\UserGpuPreferences]")
                print(f'"DirectXUserGlobalSettings"="HighPerfAdapter={ven_code}&{dev_code}&{subsys_code};"')
                #print(f'"DirectXUserGlobalSettings"="HighPerfAdapter={P102}"')
                print(f'"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"="SpecificAdapter={ven_code}&{dev_code}&{subsys_code};"')

                # 你可以继续添加更多的 print 语句来写入更多的行

            print("This will be printed to the screen again.")

            print("Windows Registry Editor Version 5.00")
            print("[HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\DirectX\\UserGpuPreferences]")
            print(f'"DirectXUserGlobalSettings"="HighPerfAdapter={P102}"')

        if 'AMD' in adapter.Name:
            ven_code, dev_code, subsys_code = extract_info(pnp_device_id)
            print(f"VEN_ Code: {ven_code}")
            print(f"DEV_ Code: {dev_code}")
            print(f"SUBSYS_ Code: {subsys_code}")
            print(f"{ven_code}&{dev_code}&{subsys_code};")
            P102 = (f"{ven_code}&{dev_code}&{subsys_code};")
            class RedirectStdout:
                def __init__(self, new_target):
                    self._new_target = new_target

                def __enter__(self):
                    self._old_target, sys.stdout = sys.stdout, self._new_target

                def __exit__(self, exc_type, exc_val, exc_tb):
                    sys.stdout = self._old_target

        # 假设你要打印的内容包括多行
            with open("regAMD.reg", "w") as f, RedirectStdout(f):
                
                print("Windows Registry Editor Version 5.00")
                print("[HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\DirectX\\UserGpuPreferences]")
                print(f'"DirectXUserGlobalSettings"="HighPerfAdapter={P102}"')

                # 你可以继续添加更多的 print 语句来写入更多的行

            print("This will be printed to the screen again.")

            print("Windows Registry Editor Version 5.00")
            print("[HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\DirectX\\UserGpuPreferences]")
            print(f'"DirectXUserGlobalSettings"="HighPerfAdapter={P102}"')
        if 'INTEL' in adapter.Name:
            ven_code, dev_code, subsys_code = extract_info(pnp_device_id)
            print(f"VEN_ Code: {ven_code}")
            print(f"DEV_ Code: {dev_code}")
            print(f"SUBSYS_ Code: {subsys_code}")
            print(f"{ven_code}&{dev_code}&{subsys_code};")
            P102 = (f"{ven_code}&{dev_code}&{subsys_code};")
            class RedirectStdout:
                def __init__(self, new_target):
                    self._new_target = new_target

                def __enter__(self):
                    self._old_target, sys.stdout = sys.stdout, self._new_target

                def __exit__(self, exc_type, exc_val, exc_tb):
                    sys.stdout = self._old_target

        # 假设你要打印的内容包括多行
            with open("reg{ven_code}.reg", "w") as f, RedirectStdout(f):
                
                print("Windows Registry Editor Version 5.00")
                print("[HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\DirectX\\UserGpuPreferences]")
                print(f'"DirectXUserGlobalSettings"="HighPerfAdapter={P102}"')

                # 你可以继续添加更多的 print 语句来写入更多的行

            print("This will be printed to the screen again.")

            print("Windows Registry Editor Version 5.00")
            print("[HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\DirectX\\UserGpuPreferences]")
            print(f'"DirectXUserGlobalSettings"="HighPerfAdapter={P102}"')
        else:
            ven_code, dev_code, subsys_code = extract_info(pnp_device_id)
            print(f"VEN_ Code: {ven_code}")
            print(f"DEV_ Code: {dev_code}")
            print(f"SUBSYS_ Code: {subsys_code}")
            print(f"{ven_code}&{dev_code}&{subsys_code};")
            P102 = (f"{ven_code}&{dev_code}&{subsys_code};")
            class RedirectStdout:
                def __init__(self, new_target):
                    self._new_target = new_target

                def __enter__(self):
                    self._old_target, sys.stdout = sys.stdout, self._new_target

                def __exit__(self, exc_type, exc_val, exc_tb):
                    sys.stdout = self._old_target

        # 假设你要打印的内容包括多行
            with open("regorther.reg", "w") as f, RedirectStdout(f):
                
                print("Windows Registry Editor Version 5.00")
                print("[HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\DirectX\\UserGpuPreferences]")
                print(f'"DirectXUserGlobalSettings"="HighPerfAdapter={P102}"')

                # 你可以继续添加更多的 print 语句来写入更多的行

            print("This will be printed to the screen again.")

            print("Windows Registry Editor Version 5.00")
            print("[HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\DirectX\\UserGpuPreferences]")
            print(f'"DirectXUserGlobalSettings"="HighPerfAdapter={P102}"')

        
        print("")
def add_key(hive, path, key_name):
    """在指定的路径下添加一个键"""
    try:
        reg.CreateKey(hive, path + '\\' + key_name)
        print(f"Key '{key_name}' created successfully.")
    except FileExistsError:
        print(f"Key '{key_name}' already exists.")

def set_value(hive, path, key_name, value_name, value_data, value_type):
    """在指定的键下设置值"""
    try:
        key = reg.OpenKey(hive, path + '\\' + key_name, 0, reg.KEY_WRITE)
        reg.SetValueEx(key, value_name, 0, value_type, value_data)
        reg.CloseKey(key)
        print(f"Value '{value_name}' set successfully.")
    except FileNotFoundError:
        print(f"Key '{key_name}' does not exist.")

def delete_key(hive, path, key_name):
    """删除指定的键（如果键为空）"""
    try:
        reg.DeleteKey(hive, path + '\\' + key_name)
        print(f"Key '{key_name}' deleted successfully.")
    except OSError:
        print(f"Key '{key_name}' cannot be deleted.")

# 使用示例
#P102 = "10DE&1B07&247419DA;"
P102 = "{ven_code}&{dev_code}&{subsys_code};"
hive = reg.HKEY_CURRENT_USER
path = "SOFTWARE\\Microsoft\\DirectX"
key_name = "UserGpuPreferences"
value_name = "DirectXUserGlobalSettings"
value_data = "HighPerfAdapter="+ P102
value_type = reg.REG_SZ

# 添加键
add_key(hive, path, key_name)

# 设置值
set_value(hive, path, key_name, value_name, value_data, value_type)
if __name__ == "__main__":
    get_display_adapters()
